<template>
  <el-form :model="formdata" label-width="auto" style="max-width: 600px" ref="ruleFormRef" :rules="data.rules">
    <el-form-item :label="$t('machine.software.softwareVer')+':'" prop="mv_id">
      <el-select :placeholder="$t('message.selectVersion')" v-model="formdata.mv_id" filterable>
        <el-option v-for="item in props.version" :key="item.value" :label="item.value + '---' + item.label"
          :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('machine.name')+':'" prop="machineList">
      <el-select :placeholder="$t('message.selectDeviceNumber')" v-model="data.m_idarr" multiple filterable>
        <el-option v-for="item in filteredMachines" :key="item.m_id" :label="item.machine_id+'-'+'('+item.machine_name+')'" :value="item.m_id" />
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('date.updateDate')+':'">
      <el-date-picker v-model="data.publish_time" type="datetime" :placeholder="$t('message.selectDate')" value-format="x"
        :editable="false" :disabled-date="disabledDate" />
    </el-form-item>
    <div class="w-full text-center">
      <div class="inline-block">
        <el-button type="primary" @click="submit(ruleFormRef)">{{ $t('public.save')}}</el-button>
        <el-button @click="cancel">{{ $t('public.cancel')}}</el-button>
      </div>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n' 
const { t: $t } = useI18n()
import { ref } from 'vue'
import { getmachineList } from "@/api/machine";
import { FormInstance } from "element-plus";
let ruleFormRef = ref<any>()
let emit = defineEmits(['plan'])
// 日期选择
let disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}
let formdata = reactive({
  mv_id: [],
  m_id: {
    type: String,
    default: '',
  },
  publish_time: {
    type: Number,
    default: new Date().getTime() / 1000
  },

})

let data = reactive({
  mtloading: false, // 加载
  list: [], // 列表信息
  m_idarr: [],
  publish_time: '',
  machines: { // 筛选数据
    page: 1,
    pageNum: 15
  },
  machineslist: [],
  total: 0,
  rules: { // 表单验证
    mv_id: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur' },
    machineList: { required: true, message:  $t('message.pleaseEnter'), trigger: 'blur', type: Array },
  },
})

interface Props {
  updateplan?: Object,
  version?: { label: string, value: number }[]
}

let props = withDefaults(defineProps<Props>(), {
  updateplan: () => { return {} },
  version: () => []
})
// 新增：根据选中的 mv_id 过滤 machineslist（排除 version 相同的机器）
const filteredMachines = computed(() => {
  // 没有选择版本时直接返回全部
  if (!formdata.mv_id) return data.machineslist
  // 找到选中版本的 label（版本号字符串）
  const ver = props.version.find(v => v.value === formdata.mv_id)
  if (!ver) return data.machineslist
  // 过滤出 version 字段与选中版本不同的机器（假设后端机器对象中 version 字段为 version 或 version_no，根据实际字段调整）
  return data.machineslist.filter(item => item.version !== ver.label && item.version_no !== ver.label)
})

// 新增：当选择版本后，如果已选的机器中有被过滤掉的，移除它们
watch(() => formdata.mv_id, (newVal) => {
  if (!newVal) return
  const ver = props.version.find(v => v.value === newVal)
  if (!ver) return
  data.m_idarr = data.m_idarr.filter(id => {
    const m = data.machineslist.find(x => x.m_id === id)
    if (!m) return false
    return m.version !== ver.label && m.version_no !== ver.label
  })
})

//时间格式
// 查询列表
// 查询设备列表
let getmachines = () => {
  data.mtloading = true
  getmachineList().then(res => {
    data.mtloading = false
    if (res.state == 200) {
      data.machineslist = res.data
      data.total = res.data.total
    }
  })
}
// 取消按钮
let cancel = () => {
  emit('plan', false)
}

// 保存按钮
let submit = (formEl: FormInstance | undefined) => {
  //props.updateplan
  formdata.m_id = data.m_idarr.toString()
  formdata.publish_time = Math.floor(data.publish_time / 1000)
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      emit('plan', formdata)
    }

  })
}


getmachines()
</script>
